import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHistory } from "vue-router";
import { RedirectRoute, RootRoute, LoginRoute } from "../router/base";
import { createPermissionGuard } from "./guard/permission";
import { createTagsGuard } from "./guard/tags";
import { LoadingManager } from "@/utils/loadingManager";

import { IModuleType } from "./types";

const modules = import.meta.glob<IModuleType>("./modules/**/*.ts", {
  eager: true,
});

// 自动导入路由信息
const routeModuleList: RouteRecordRaw[] = Object.keys(modules).reduce(
  (list, key) => {
    const mod = modules[key].default ?? {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    return [...list, ...modList];
  },
  []
);

function sortRoute(a, b) {
  return (a.meta?.sort ?? 0) - (b.meta?.sort ?? 0);
}

//需要验证权限
export const asyncRoutes = [...routeModuleList];

// 排序之后的路由信息【所有路由信息】
const businessRoutes = routeModuleList.sort(sortRoute);

//普通路由 无需验证权限
export const constantRouter: RouteRecordRaw[] = [
  LoginRoute,
  RootRoute,
  RedirectRoute,
  ...businessRoutes,
];

function scrollBehavior(_to, _from, savedPosition) {
  if (!import.meta.env.VITE_APP_ROUTER_COORDINATE) {
    return () => ({ left: 0, top: 0 });
  }
  if (savedPosition) {
    // savedPosition 会在你使用浏览器前进或后退按钮时候生效
    // savedPosition: 会记录滚动条的坐标，点击"后退/前进" 时的记录值(x:?,y:?)
    return savedPosition;
  } else {
    return { x: 0, y: 0 }; // 期望滚动的位置
  }
}

const router = createRouter({
  history: createWebHistory(),
  strict: true, // sensitive 路径是否区分大小写   //strict 不区分
  scrollBehavior,
  routes: constantRouter,
});

router.afterEach(() => {
  LoadingManager.hide();
});

// 注册权限守卫
createPermissionGuard(router);
createTagsGuard(router);

export function setupRouter() {
  createTagsGuard(router);
}

export default router;
